package Arraylist;

import java.util.Arrays;

public class ArrayListImplement implements Define{
    public static final int default_capacity=5;
    public int[] array=new int[ArrayListImplement.default_capacity];
    public int usesize;    //数组中存储了多少个有序数据
    @Override
    public void display() {
        for (int i = 0; i < this.usesize; i++) {
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }

    @Override
    public int size() {
        return this.usesize;
    }

    @Override
    public boolean contains(int findnum) {
        for (int i = 0; i < this.usesize; i++) {
            if(array[i]==findnum) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int findnum) {
        for (int i = 0; i < this.usesize; i++) {
            if(array[i]==findnum) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void add(int data) {
        if(this.isFull()) {
            resize();
        }
        this.array[this.usesize]=data;
        this.usesize++;
    }

    @Override
    public boolean isFull() {
        return this.usesize==this.array.length;
    }
    @Override
    public boolean isEmpty() {
        return this.usesize==0;
    }
    @Override
    public void resize() {
        this.array= Arrays.copyOf(this.array,array.length*2);
    }

    @Override
    public void add(int pos, int data) {
        this.checkIndex(pos);
        if(this.isFull()) {
            resize();
        }
        for (int i = this.usesize-1; i>=pos  ; i--) {
            this.array[i+1]=this.array[i];
        }
        this.array[pos]=data;
        this.usesize++;
    }

    @Override
    public void checkIndex(int pos) {
        if(pos<0||pos>this.usesize) {     //如果pos位置在usesize之后就不满足顺序表的有序原则，因为usesize这个位置是空的
            throw new CheckAddIndexOutOfException("pos位置有误!");
        }
    }

    @Override
    public int get(int pos) {
        this.checkIndex(pos);
        return this.array[pos];
    }

    @Override
    public void remove(int toremove) {
        if(this.isEmpty()) {
            System.out.println("顺序表为空，无法删除!");
            return;
        }
        for (int i = 0; i < this.usesize; i++) {
            if(this.array[i]==toremove) {
                for (int j = i; j < this.array.length-1; j++) {
                    this.array[j]=this.array[j+1];
                }
                this.array[--this.usesize]=0;
                return;
            }
        }
        System.out.println("没有数字可以删除!");
    }

    @Override
    public void clear() {
        Arrays.fill(this.array,0);
        this.usesize=0;
    }
}
